package com.ohuang.launcher;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class PermissionInterceptor {
public static final String TAG="PermissionInterceptor";
    public static boolean isHooked = false;

    public static Object mObject=null;

    public synchronized static void hook() {
        if (isHooked) {
            return;
        }
        isHooked = true;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            try {
                Class<?> aClass = Class.forName("android.app.ActivityTaskManager");
                Field field_IActivityTaskManagerSingleton = aClass.getDeclaredField("IActivityTaskManagerSingleton");
                field_IActivityTaskManagerSingleton.setAccessible(true);
                Object iActivityTaskManagerSingleton = field_IActivityTaskManagerSingleton.get(null);

                Class<?> aClass_Singleton = Class.forName("android.util.Singleton");
                Field field_mInstance = aClass_Singleton.getDeclaredField("mInstance");
                field_mInstance.setAccessible(true);
                Method method_get = aClass_Singleton.getDeclaredMethod("get");
                Object mInstant = method_get.invoke(iActivityTaskManagerSingleton);
                mObject=mInstant;
                Class<?> aClass_IActivityTaskManager = Class.forName("android.app.IActivityTaskManager");
                Object mInstantProxy = Proxy.newProxyInstance(aClass_IActivityTaskManager.getClassLoader(), new Class[]{aClass_IActivityTaskManager}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        if ("startActivity".equals(method.getName())) {
                            Intent intent = (Intent) args[3];
                            if (isInterceptor(mObject,method,args,intent)) {
                                return 0;
                            }
                        }
                        return method.invoke(mInstant, args);
                    }
                });
                field_mInstance.set(iActivityTaskManagerSingleton, mInstantProxy);

            } catch
            (ClassNotFoundException | IllegalAccessException | NoSuchMethodException |
             InvocationTargetException | NoSuchFieldException
                            e) {
                e.printStackTrace();
            }
        } else {
            try {
                Class<?> aClass = Class.forName("android.app.ActivityManager");
                Field field_IActivityTaskManagerSingleton = aClass.getDeclaredField("IActivityManagerSingleton");
                field_IActivityTaskManagerSingleton.setAccessible(true);
                Object iActivityTaskManagerSingleton = field_IActivityTaskManagerSingleton.get(null);

                Class<?> aClass_Singleton = Class.forName("android.util.Singleton");
                Field field_mInstance = aClass_Singleton.getDeclaredField("mInstance");
                field_mInstance.setAccessible(true);
                Method method_get = aClass_Singleton.getDeclaredMethod("get");
                Object mInstant = method_get.invoke(iActivityTaskManagerSingleton);
                mObject=mInstant;
                Class<?> aClass_IActivityManager = Class.forName("android.app.IActivityManager");
                Object mInstantProxy = Proxy.newProxyInstance(aClass_IActivityManager.getClassLoader(), new Class[]{aClass_IActivityManager}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        if ("startActivity".equals(method.getName())) {
                            Intent intent = (Intent) args[2];
                            if (isInterceptor(mObject,method,args,intent)) {
                                return 0;
                            }
                        }
                        return method.invoke(mInstant, args);
                    }
                });

                field_mInstance.set(iActivityTaskManagerSingleton, mInstantProxy);

            } catch
            (ClassNotFoundException | IllegalAccessException | NoSuchMethodException | InvocationTargetException | NoSuchFieldException
                            e) {
                e.printStackTrace();
            }

        }

    }

    public synchronized static void unHook(){
        if (isHooked&&mObject!=null){
            isHooked=false;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                try {
                    Class<?> aClass = Class.forName("android.app.ActivityTaskManager");
                    Field field_IActivityTaskManagerSingleton = aClass.getDeclaredField("IActivityTaskManagerSingleton");
                    field_IActivityTaskManagerSingleton.setAccessible(true);
                    Object iActivityTaskManagerSingleton = field_IActivityTaskManagerSingleton.get(null);

                    Class<?> aClass_Singleton = Class.forName("android.util.Singleton");
                    Field field_mInstance = aClass_Singleton.getDeclaredField("mInstance");
                    field_mInstance.setAccessible(true);
                    field_mInstance.set(iActivityTaskManagerSingleton, mObject);

                } catch
                (ClassNotFoundException | IllegalAccessException | NoSuchFieldException
                                e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    Class<?> aClass = Class.forName("android.app.ActivityManager");
                    Field field_IActivityTaskManagerSingleton = aClass.getDeclaredField("IActivityManagerSingleton");
                    field_IActivityTaskManagerSingleton.setAccessible(true);
                    Object iActivityTaskManagerSingleton = field_IActivityTaskManagerSingleton.get(null);
                    Class<?> aClass_Singleton = Class.forName("android.util.Singleton");
                    Field field_mInstance = aClass_Singleton.getDeclaredField("mInstance");
                    field_mInstance.setAccessible(true);
                    field_mInstance.set(iActivityTaskManagerSingleton, mObject);

                } catch
                (ClassNotFoundException | IllegalAccessException | NoSuchFieldException
                                e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private static boolean isInterceptor(Object proxy, Method method, Object[] args,Intent intent) {

        Activity resumeActivity = ActivityManager.getInstance().getResumeActivity();
        if ("android.content.pm.action.REQUEST_PERMISSIONS".equals(intent.getAction())&&resumeActivity!=null){
            Log.d(TAG, "isInterceptor: true");
                AlertDialog dialog = new AlertDialog.Builder(resumeActivity)
                        .setTitle("注意")//设置对话框的标题
                        .setMessage("此应用需获得使用此应用的权限")//设置对话框的内容
                        //设置对话框的按钮
                        .setCancelable(false)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                try {
                                    method.invoke(proxy,args);
                                } catch (IllegalAccessException | InvocationTargetException ignored) {

                                }
                                dialog.dismiss();
                            }
                        }).create();
                dialog.show();

            return true;
        }
        return false;
    }


}
